<?php
/**
 * 条形码
 * @filesource http://www.barcodephp.com
 * @author cjli
 */

class BarCode
{
	/**
	 * 获取条形码图片
	 * @param string $text 条形码内容
	 * @param string $code_type 条形码码制
	 * @param boolean $isfont 是否显示文字
	 * @return html
	 */
	static function getBarCode($text, $code_type = '', $isfont = true)
	{
		if(empty($code_type)){
			$code_type = 'BCGcode93';
		}
		$codeList = array('BCGcodabar','BCGcode11','BCGcode39','BCGcode39extended','BCGcode93','BCGcode128','BCGean8','BCGean13','BCGisbn','BCGi25','BCGs25','BCGmsi','BCGupca','BCGupce','BCGupcext2','BCGupcext5','BCGpostnet','BCGothercode');
		if(!in_array($code_type, $codeList)){
			die('码制不正确');
		}
		
		if(empty($text)){
			die('条形码文字不能为空');
		}
		// Including all required classes
		vendor('barcodegen.BCGFont');
		vendor('barcodegen.BCGColor');
		vendor('barcodegen.BCGDrawing');

		// Including the barcode technology
		vendor('barcodegen.'.$code_type.'#barcode'); 
		// Loading Font
		if($isfont){
			$font = new BCGFont(ROOT_PATH.'/statics/font/arial.ttf', 18);
		}

		// The arguments are R, G, B for color.
		$color_black = new BCGColor(0, 0, 0);
		$color_white = new BCGColor(255, 255, 255); 

		$code = new $code_type();
		$code->setScale(2); // Resolution
		$code->setThickness(30); // Thickness
		$code->setForegroundColor($color_black); // Color of bars
		$code->setBackgroundColor($color_white); // Color of spaces
		$code->setFont($font); // Font (or 0)
		$code->parse($text); // Text

		
		/* Here is the list of the arguments
		1 - Filename (empty : display on screen)
		2 - Background color */
		$drawing = new BCGDrawing('', $color_white);
		$drawing->setBarcode($code);
		$drawing->draw();

		// Header that says it is an image (remove it if you save the barcode to a file)
		header('Content-Type: image/png');
		
		// Draw (or save) the image into PNG format.
		return	$drawing->finish(BCGDrawing::IMG_FORMAT_PNG);
	}
}